package com.mall.order.services;

import com.mall.commons.tool.utils.TradeNoUtils;
import com.mall.order.OrderCoreService;
import com.mall.order.biz.TransOutboundInvoker;
import com.mall.order.biz.context.AbsTransHandlerContext;
import com.mall.order.biz.factory.OrderProcessPipelineFactory;
import com.mall.order.constants.OrderConstants;
import com.mall.order.consumer.producer.OrderDelayMQProducer;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.OrderShipping;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import com.mall.promo.dto.SecKillRequest;
import com.mall.shopping.IProductService;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.ProductDetailDto;
import com.mall.shopping.dto.ProductDetailRequest;
import com.mall.shopping.dto.ProductDetailResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.UUID;

/**
 *  ciggar
 * create-date: 2019/7/30-上午10:05
 * @author Administrator
 */
@Slf4j
@Component
@Service
public class OrderCoreServiceImpl implements OrderCoreService {

	@Autowired
	OrderMapper orderMapper;

	@Reference(check = false)
	IProductService iProductService;

	@Autowired
	OrderItemMapper orderItemMapper;

	@Autowired
	OrderShippingMapper orderShippingMapper;

	@Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

	@Autowired
	OrderDelayMQProducer orderDelayMQProducer;


	/**
	 * 创建订单的处理流程
	 *
	 * @param request
	 * @return
	 */
	@Override
	public CreateOrderResponse createOrder(CreateOrderRequest request) {
		CreateOrderResponse response = new CreateOrderResponse();
		try {
			//创建pipeline对象
			TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

			//启动pipeline
			invoker.start(); //启动流程（pipeline来处理）

			//获取处理结果
			AbsTransHandlerContext context = invoker.getContext();

			//把处理结果转换为response
			response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);
		} catch (Exception e) {
			log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
			ExceptionProcessorUtils.wrapperHandlerException(response, e);
		}
		return response;
	}

	@Override
	public void changeOrderStatus(String orderId, String payStatusPayed) {
		Example example = new Example(Order.class);
		example.createCriteria().andEqualTo("orderId",orderId);
		Order order = new Order();
		order.setStatus(Integer.parseInt(payStatusPayed));
		orderMapper.updateByExampleSelective(order,example);
	}

	@Override
	public void createPromoOrder(SecKillRequest request) {
		//向order表里插入数据
		Order order = new Order();
		//组装参数
		String orderId = TradeNoUtils.generateTradeNo();
		order.setUserId(request.getUserId());
		order.setPayment(request.getPromoPrice());
		order.setOrderId(orderId);
		order.setStatus(OrderConstants.ORDER_STATUS_INIT);
		order.setCreateTime(new Date());
		order.setUpdateTime(new Date());
		orderMapper.insert(order);
		//向orderItem表插入数据


		ProductDetailRequest productDetailRequest = new ProductDetailRequest();
		productDetailRequest.setId(request.getProductId());
		ProductDetailResponse productDetailResponse = iProductService.getProductDetail(productDetailRequest);
		ProductDetailDto productDetail = productDetailResponse.getProductDetailDto();
		OrderItem orderItem = new OrderItem();
		orderItem.setId(UUID.randomUUID().toString());
		orderItem.setItemId(request.getProductId());
		orderItem.setOrderId(orderId);
		orderItem.setNum(1);
		orderItem.setTitle(productDetail.getProductName());

		double price = request.getPromoPrice().doubleValue();
		orderItem.setPrice(price);
		orderItem.setTotalFee(price);
		String productImageBig = productDetail.getProductImageBig();
		orderItem.setPicPath(productImageBig);
		orderItem.setStatus(1);
		orderItemMapper.insert(orderItem);

		//向orderShipping表插入数据
		OrderShipping orderShipping = new OrderShipping();
		orderShipping.setOrderId(orderId);
		orderShipping.setReceiverName(request.getUsername());
		orderShipping.setReceiverPhone(request.getTel());
		orderShipping.setReceiverAddress(request.getStreetName());
		orderShipping.setCreated(new Date());
		orderShipping.setUpdated(new Date());
		orderShippingMapper.insert(orderShipping);

		//超时取消订单
		orderDelayMQProducer.sendMessage(orderId);
	}
}
